// pages/user/bind.js
const App = getApp()
import Util from '../../utils/util'

Page({

  data: {
    init: false, // 界面是否初始化中
    loading: false, // 是否loading状态
    finish: false, // 是否业务完成
    uid: '',
    user: {},
    code: '',
  },
  // 页面加载完成
  onLoad(options) {
    this.waitForReady(options)
  },
  waitForReady(options) {
    if (App.Global.OpenId) {
      this.execLoad(options)
    } else {
      setTimeout(() => {
        this.waitForReady(options)
      }, 200);
    }
  },
  execLoad(options) {
    App.doPost({
      uri: '/app/user/account/wxmn/clerk/info',
      body: {
        id: options.uid,
      },
      fnSucc: resp => {
        this.setData({
          user: resp.data,
          uid: options.uid,
          init: true
        })
      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
      },
      fnComp: () => {
        this.setData({
          loading: false
        })
      }
    })
  },
  // 提交绑定用户
  doSubmitBind() {
    if (!this.data.code || this.data.code.length < 4 || this.data.code.length > 10) {
      Util.Notify.warn(`请填写正确的绑定码，长度[4-10]个字符`)
      return
    }
    this.setData({
      loading: true
    })
    App.doPost({
      uri: '/app/user/account/wxmn/clerk/bind',
      body: {
        appid: App.Global.AppId,
        openid: App.Global.OpenId,
        id: this.data.uid,
        pwd: this.data.code
      },
      fnSucc: () => {
        wx.showModal({
          title: `绑定成功`,
          content: `您已成功绑定${this.data.user.name}`,
          showCancel: false,
          success(res) {
            if (res.confirm) {
              this.setData({
                finish: true
              })
              wx.navigateTo({
                url: '/pages/splash/splash'
              })
            }
          }
        })
      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
      },
      fnComp: () => {
        this.setData({
          loading: false
        })
      }
    })
  }
})